package com.bear.fastrepair.mvvm.ui.employee.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bear.fastrepair.MainActivity
import com.bear.fastrepair.R
import com.bear.fastrepair.base.BaseFragment
import com.bear.fastrepair.databinding.FragmentEmployeeOrderBinding
import com.bear.fastrepair.entity.FooterItem
import com.bear.fastrepair.entity.RecordItem
import com.bear.fastrepair.mvvm.ui.MainViewModel
import com.bear.fastrepair.mvvm.ui.MainViewModelFactory
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModel
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModelFactory
import com.bear.fastrepair.mvvm.ui.employee.adapter.OrderAdapter
import com.bear.fastrepair.utils.SharedPreferencesHelper
import com.bear.fastrepair.utils.WORK_STATUS_KEY
import com.bear.fastrepair.utils.launch
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.bottomnavigation.BottomNavigationView

class EmployeeOrderFragment : BaseFragment<FragmentEmployeeOrderBinding>() {

    private lateinit var viewModel: EmployeeViewModel
    private lateinit var globalViewModel: EmployeeViewModel

    private lateinit var mainViewModel: MainViewModel
    override val title: String
        get() = getString(R.string.order_center)

    private var loading = false

    @SuppressLint("NotifyDataSetChanged")
    override fun init() {
        val main = requireActivity() as MainActivity
        val navi = main.findViewById<BottomNavigationView>(R.id.bottom_navi_employee)
        navi?.visibility = View.VISIBLE
        viewModel = ViewModelProvider(
            this,
            EmployeeViewModelFactory()
        ).get(EmployeeViewModel::class.java)
        globalViewModel = ViewModelProvider(
            requireActivity(),
            EmployeeViewModelFactory()
        ).get(EmployeeViewModel::class.java)
        mainViewModel =
            ViewModelProvider(
                requireActivity(),
                MainViewModelFactory()
            ).get(MainViewModel::class.java)
        mainViewModel.loginStatus()
//        main.setOrderListener {
//            LogUtils.i("content $it")
//            ToastUtils.showLong("有新的订单派发给你哦~")
//        }
        main.setNewOrderListener {
            val data = Bundle()
            data.putString("record", it)
            findNavController().navigate(R.id.orderDetailFragment, data)
        }

        // 列表
        val adapter = OrderAdapter(ArrayList(), globalViewModel, requireContext()).apply {
            itemClick = { record, _ ->
//                viewModel.getOrderById(record.id)
                val data = Bundle()
                data.putString("record", record.id)
                findNavController().navigate(R.id.orderDetailFragment, data)
            }
        }
        binding.rvOrder.adapter = adapter

        binding.rvOrder.layoutManager = LinearLayoutManager(requireContext())
        globalViewModel.getPersonalInfo()

        val orderType = if (binding.currentOrderList.isChecked) 0 else 1
        viewModel.getOrderInfoPage(1, 5, orderType)
        viewModel.getOrderInfoPage.observe(viewLifecycleOwner) {
            binding.refreshLl.isRefreshing = false
            loading = false
            if (it.pageData.code != 0) {
                LogUtils.i("error msg is ${it.pageData.msg}")
                if (it.pageData.code == 10002) {
                    ToastUtils.showLong("${it.pageData.msg} 请重新登录")
                    findNavController().popBackStack()
                    findNavController().navigate(R.id.loginFragment)
                }
                return@observe
            }
            val records =
                it.pageData.data.records?.map { record -> RecordItem(record) } ?: return@observe
//            val oldData = ArrayList<ItemTypeOrder>()
//            oldData.addAll(adapter.data)
            val oldCont = adapter.itemCount
            // 此处逻辑注意
            val position = if (oldCont - 1 <= 0) 0 else oldCont
            if (!it.loadMore) {
                adapter.data.clear()
                adapter.data.addAll(records)
                if (records.size >= 5) {
                    adapter.data.add(FooterItem())
                }
                adapter.notifyDataSetChanged()
            } else {
//                if (adapter.data.isNotEmpty()) adapter.data.removeLast()
                adapter.data.removeAll { item -> item is FooterItem}
                adapter.data.addAll(records)
                if (it.currentPage != it.pageData.data.pageTotal) {
                    adapter.data.add(FooterItem())
                }
                adapter.notifyItemRangeInserted(position, adapter.data.size)
            }
        }

        globalViewModel.personalInfo.observe(viewLifecycleOwner) {
            if (it.code == 0) {
                viewModel.launch {
                    SharedPreferencesHelper.putInfo(WORK_STATUS_KEY, it.data.workStatus)
                }
                if (!viewModel.webSocketStart) {
                    viewModel.webSocketStart = true
                    main.startWebSocket(it.data.id)
                }
            }
        }

        viewModel.clockIn.observe(viewLifecycleOwner) {
            if (it != -1) {
                binding.rvOrder.adapter?.notifyItemChanged(it)
            }
        }

//        viewModel.getOrderInfoDetail.observe(viewLifecycleOwner) {
//            when (it.code) {
//                0 -> {
////                    findNavController().navigate(R.id.orderDetailFragment)
//                }
//                -1 -> {
//                    // ignore
//                }
//                else -> {
//                    ToastUtils.showLong("无该订单，请确认服务单号")
//                }
//            }
//        }
        binding.refreshLl.setOnRefreshListener {
            if (loading) return@setOnRefreshListener
            viewModel.getOrderInfoPage(1, 5, if (binding.currentOrderList.isChecked) 0 else 1)
        }

        binding.rvOrder.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            private var scrollingUp = false
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (binding.refreshLl.isRefreshing) {
                        ToastUtils.showLong("加载中")
                        return
                    }
                    val layoutManager = binding.rvOrder.layoutManager as LinearLayoutManager
                    val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                    if (lastVisibleItemPosition + 1 == adapter.itemCount) {
                        viewModel.getOrderInfoPage.value ?: return
                        val currentPage = viewModel.getOrderInfoPage.value!!.currentPage
                        if (currentPage == viewModel.getOrderInfoPage.value!!.pageData.data.pageTotal) {
                            ToastUtils.showShort("已加载全部数据")
                            return
                        }
                        if (!loading && scrollingUp) {
                            loading = true
                            viewModel.getOrderInfoPage(
                                currentPage + 1,
                                5,
                                if (binding.currentOrderList.isChecked) 0 else 1,
                                true
                            )
                        }
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                scrollingUp = dy > 0
            }
        })
        binding.btnSearch.setOnClickListener {
            val id = binding.searchEdit.text.toString()
            if (id.isEmpty()) {
                ToastUtils.showLong("请输入服务单号！")
                return@setOnClickListener
            }
            viewModel.getOrderById(id)
        }

        binding.orderStatusLl.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.current_order_list -> viewModel.getOrderInfoPage(1, 5, 0)
                R.id.history_order_list -> viewModel.getOrderInfoPage(1, 5, 1)
            }
        }
    }
}